package com.gin.kotlin.gf2gamecommunity.pagingsource

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.routes.TopicListRoute
import com.gin.kotlin.response.topic.TopicInfo
import com.gin.kotlin.response.topic.TopicPage
import retrofit2.await

class TopicInfoPagingSource(private var route: TopicListRoute) : PagingSource<Int, TopicInfo>() {
    private val cachedData = hashMapOf<Int, TopicPage>()

    init {
        Log.i(TAG, "实例化")
    }

    override fun getRefreshKey(state: PagingState<Int, TopicInfo>): Nothing? {
        Log.i(TAG, "getRefreshKey: ${state.config.pageSize}")
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, TopicInfo> {
        val page = params.key ?: 1
        val cache = cachedData[page]
        if (cache != null) {
            Log.i(TAG, "缓存命中: page = $page")
            return handleTopicPage(cache, page)
        }
        val (queryType, userId, themeId, categoryId) = route
        Log.i(TAG, "load: $page, size:${params.loadSize}, queryType:$queryType userId:$userId themeId:$themeId categoryId:$categoryId")
        try {
            // 发送请求
            val response = App.INSTANCE.api.topicApi.list(
                queryType = route.queryType,
                userId = route.userId,
                themeId = route.themeId,
                categoryId = route.categoryId,
                sortType = route.sortType,
                hotValue = route.hotValue,
                lastTid = route.lastTid,
                pubTime = route.pubTime,
                replyTime = route.replyTime,
            ).await()

            // 响应结果
            val topicPage = response.data ?: return LoadResult.Page(listOf(), null, null)

            // //  如果为第一页，请求置顶贴
            // if (page == 1 && route.categoryId!=null) {
            //     val topRes = App.INSTANCE.api.topicApi.getTop(route.categoryId!!).await()
            //     topRes.data?.map { top ->
            //         TopicInfo().apply {
            //             createTime = top.createTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime().toString().replace("T", " ")
            //             topicId = top.topicId
            //             title = "[置顶][${top.type}] ${top.title}"
            //         }
            //     }?.toMutableList()?.also { list ->
            //         list.addAll(topicPage.list)
            //         topicPage.list = list
            //     }
            // }

            // 保存缓存数据
            cachedData[page] = topicPage
            // 修改翻页数据
            return handleTopicPage(topicPage, page)
        } catch (e: Exception) {
            // 处理异常
            e.printStackTrace()
            return LoadResult.Error(e)
        }
    }

    private fun handleTopicPage(
        topicPage: TopicPage,
        page: Int
    ): LoadResult.Page<Int, TopicInfo> {
        route = route.copy(
            hotValue = topicPage.hotValue,
            lastTid = topicPage.lastTid,
            pubTime = topicPage.pubTime,
            replyTime = topicPage.replyTime,
        )
        // 根据响应结果决定是否有下一页
        val nextKey = if (topicPage.nextPage) page + 1 else null
        // 返回结果
        return LoadResult.Page(topicPage.list, null, nextKey)
    }

    companion object {
        private val TAG = TopicInfoPagingSource::class.java.simpleName
    }
}